package mobi.pfff.rest.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import mobi.pfff.rest.bean.User;

/**
 * 用户客户端 测试资源
 * @date 2015年1月6日 下午2:14:40
 * @author pfff
 */
public class UserClient {

	private static String serverUri = "http://localhost:8080/RESTDemo/rest"; // 接口的访问地址
	
	public static void main(String[] args) {
		
		addUser();
		getAllUsers();
		updateUser();
		getUserById();
		deleteUser();
		getAllUsers();
	}
	
	/**
	 * 新增用户
	 */
	private static void addUser() {
		
		System.out.println("----- 添加用户 -----");
		User user = new User("007", "XiaoLi", "21");
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(serverUri + "/users");
		Response response = target.request().buildPost(Entity.entity(user, MediaType.APPLICATION_XML)).invoke();
		response.close();
	}
	
	/**
	 * 删除用户
	 */
	private static void deleteUser() {
		
		System.out.println("----- 删除用户 -----");
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(serverUri + "/users/007");
		Response response = target.request().delete();
		response.close();
	}
	
	/**
	 * 修改用户
	 */
	private static void updateUser() {
		
		System.out.println("----- 修改用户 -----");
		User user = new User("007","XiaoWang","33");
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(serverUri + "/users");
		Response response = target.request().buildPut(Entity.entity(user, MediaType.APPLICATION_XML)).invoke();
		response.close();
	}
	
	/**
	 * 根据id查询用户 
	 */
	private static void getUserById() {
		
		System.out.println("----- 根据id查询用户  -----");
		Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
		WebTarget target = client.target(serverUri + "/users/007");
		Response response = target.request().get();
		User user = response.readEntity(User.class);
		System.out.println(user.toString());
		response.close();
	}

	/**
	 * 查询所有用户 
	 */
	private static void getAllUsers() {
		
		System.out.println("----- 查询所有用户  -----");
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(serverUri + "/users");
		Response response = target.request().get();
		String value = response.readEntity(String.class);
		System.out.println(value);
		response.close(); // 关闭连接
	}
}